package com.ibiz.webapp.controller.bx;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ibiz.bx.domain.Worklist;
import com.ibiz.bx.service.WorklistService;
import com.ibiz.bx.service.dto.WorklistSearchFilter;
import com.ibiz.ibizutil.security.AuthenticationUser;
import com.ibiz.webapp.controller.bx.vo.Worklist_Grid_Main;
import com.ibiz.webapp.controller.bx.vo.Worklist_SearchForm_Default;
import com.ibiz.workflow.WFServiceImpl;

@RestController
@RequestMapping("/webapp/bx/worklist")
public class WorklistController{



    @Autowired
	private WorklistService worklistService;
	/**
	 * 获取服务对象
	*/
	protected WorklistService getService(){
		return this.worklistService;
	}
	@PostMapping(value="maingrid/update")
	public Worklist mainGridUpdate(@Validated Worklist mainItem){
		return mainItem;
	}
	@PostMapping(value="maingrid/remove")
	public ResponseEntity<Worklist> mainGridRemove(@Validated @RequestBody Map args){
	    Worklist entity =new Worklist();
	    if ( !StringUtils.isEmpty(args.get("srfkeys"))) {
			String srfkeys=args.get("srfkeys").toString();
			String srfkeyArr[] =srfkeys.split(";");
			for(String srfkey : srfkeyArr)
			{
				if(!StringUtils.isEmpty(srfkey)){
				entity.setWorklistid(srfkey);
				this.getService().remove(entity);
                }
            }
        }
		return ResponseEntity.ok().body(entity);
	}
	public Worklist mainGridGet(String worklistid){
		return null;
	}
	@PostMapping(value="maingrid/getdraft")
	public Worklist mainGridGetDraft(@Validated Worklist mainItem){
		return mainItem;
	}
	@PostMapping(value="maingrid/create")
	public Worklist mainGridCreate(@Validated Worklist mainItem){
		return mainItem;
	}
	@org.springframework.beans.factory.annotation.Value("${ibiz.filePath}")
    private String strFilePath;
	@Autowired
    private com.ibiz.ibizutil.service.IBZFILEService ibzfileService;
	/**
	 * [main]表格数据导出
	 * @param searchFilter
	 * @return
	 * @throws
	 * @throws
	 */
	@PostMapping(value="maingrid/exportdata/searchmy")
	public ResponseEntity<Page<JSONObject>> maingridExportDataSearchMy(@Validated @RequestBody WorklistSearchFilter searchFilter) throws IOException, jxl.write.WriteException {
		String fileid=com.baomidou.mybatisplus.core.toolkit.IdWorker.get32UUID();
		String localPath=ExportDataInit(fileid);//输出文件相对路径
		Page<Worklist> searchResult = this.getService().searchMy(searchFilter);//1.查询表格数据
		List<Map<String,Object>> datas=Worklist_Grid_Main.pageToListDatas(searchResult);//2.将数据转换成list
		List<Map<String,String>> colnums=Worklist_Grid_Main.getGridColumnModels();//3.获取表格列头
        java.io.File outputFile=com.ibiz.ibizutil.helper.DEDataExportHelper.output(strFilePath+localPath,colnums,datas);//4.生成导出文件
		com.ibiz.ibizutil.helper.DEDataExportHelper.saveFileData(outputFile,localPath,fileid,ibzfileService); //5.保存file表记录
		String strDownloadUrl =String.format("ibizutil/download/"+fileid);//6.回传文件路径给前台
        Page<JSONObject> resultObj=Worklist_Grid_Main.getResultPage(searchResult,strDownloadUrl);//7.获取输出对象
			return ResponseEntity.ok().body(resultObj);
	}
	/**
	 * 表格数据导出
	 * @param fileid
	 * @return
	 */
	private String ExportDataInit(String fileid) {
		java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyyMMdd");
        String filepath=dateFormat.format(new java.util.Date())+ java.io.File.separator;
        java.text.SimpleDateFormat dateFormat2 = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
		String strTempFileName = fileid+"-"+dateFormat2.format(new java.util.Date())+".xls";
		java.io.File file =new java.io.File(strFilePath+filepath);
		if(!file.exists())
           file.mkdirs();
		return filepath+strTempFileName;
	}

	@Autowired
	WFServiceImpl wfServiceImpl ;
	
	@PostMapping(value="maingrid/searchmy")
	public ResponseEntity<Page<Worklist_Grid_Main>> mainGridSearchMy(@Validated @RequestBody WorklistSearchFilter searchFilter){
			Page<Worklist> searchResult = this.getService().searchMy(searchFilter);
			
			List<Task> taskList = wfServiceImpl.findTaskByUser(AuthenticationUser.getAuthenticationUser().getUserid()) ; 
			for (Task task : taskList) {
				Worklist worklist = new Worklist() ;
				worklist.setWorklistid(task.getId());
				worklist.setStep(task.getName());
				
				
				ProcessInstance instance = wfServiceImpl.findInstance(task.getProcessInstanceId()) ;
				
				worklist.setStarttime(new SimpleDateFormat("yyyy-MM-dd").format(instance.getStartTime()));
				worklist.setStartuserid(instance.getStartUserId());
				worklist.setBusinesskey(instance.getBusinessKey());
				worklist.setWorkflowid(instance.getProcessDefinitionKey()) ;
				worklist.setWorkflowname(instance.getProcessDefinitionName());
				searchResult.getRecords().add(worklist) ;
			}
			
			Page<Worklist_Grid_Main> searchResult_vo_data =Worklist_Grid_Main.fromWorklist(searchResult);
					return ResponseEntity.ok().body(searchResult_vo_data);
	}
	
	@PostMapping(value="defaultsearchform/load")
	public void defaultSearchFormLoad(){

	}
   	@PostMapping(value="defaultsearchform/loaddraft")
	public ResponseEntity<Worklist_SearchForm_Default> defaultSearchFormLoadDraft(@Validated @RequestBody Worklist_SearchForm_Default searchform){
 		 
			WorklistSearchFilter searchfilter =searchform.toWorklistSearchFilter();
			searchform.fromWorklistSearchFilter(searchfilter);
			return ResponseEntity.ok().body(searchform);
	} 
	@PostMapping(value="defaultsearchform/search")
	public void defaultSearchFormSearch(){
			 
	} 
 }